package database

import (
	"dingbot/config"
	"dingbot/errhelp"
	"dingbot/tools"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"

	"github.com/dingdinglz/dingtools/dingjson"
	"github.com/gofiber/fiber/v2"
)

func AuthEmail(email string, password string) (string, bool) {
	url := fmt.Sprintf("http://127.0.0.1:%s/api/admins/auth-via-email", config.GetConfig().Port.PocketBase)

	payload := strings.NewReader(fmt.Sprintf("{\n    \"email\" : \"%s\",\n    \"password\" : \"%s\"\n}", email, password))

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Content-Type", "application/json")
	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := ioutil.ReadAll(res.Body)
	j := dingjson.NewFromBytes(body)
	res_token, err := j.GetString("token")
	if err != nil {
		return err.Error(), false
	}
	return res_token, true
}

func HaveCollection(name string) bool {
	index := 1
	total := 1
	token_use, _ := AuthEmail(config.GetConfig().PocketBase.User, config.GetConfig().PocketBase.Password)
	for index <= total {
		url := "http://127.0.0.1:5800/api/collections?page=" + tools.IntToString(index)
		req, _ := http.NewRequest("GET", url, nil)
		req.Header.Add("Authorization", "Admin "+token_use)
		res, _ := http.DefaultClient.Do(req)
		defer res.Body.Close()
		body, _ := ioutil.ReadAll(res.Body)
		j := dingjson.NewFromBytes(body)
		i, _ := j.GetInt("totalPages")
		total = int(i)
		flag := false
		j.ArrayEach(func(json *dingjson.DingJson) {
			name_d, _ := json.GetString("name")
			if name_d == name {
				flag = true
			}
		}, "items")
		if flag {
			return true
		}
		index++
	}
	return false
}

type SchemasModal struct {
	Name     string `json:"name"`
	Type     string `json:"type"`
	Required bool   `json:"required"`
}

func CreateCollection(name string, schemas []SchemasModal) {
	url := "http://127.0.0.1:5800/api/collections"
	token_use, _ := AuthEmail(config.GetConfig().PocketBase.User, config.GetConfig().PocketBase.Password)
	req_map := fiber.Map{}
	req_map["name"] = name
	req_map["schema"] = schemas
	j, err := dingjson.NewFromStruct(&req_map)
	if !errhelp.Tag(err, "Create Collection") {
		return
	}
	payload := strings.NewReader(j.ConventToStr())

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Admin "+token_use)
	req.Header.Add("Content-Type", "application/json")
	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
}
